<?php
namespace app\index\controller;

use think\Controller;
use think\Db;

class Forget extends Controller{
    private function SendMail($username,$qq,$name,$VertifyCode)   //发送激活邮件
    {

        $tomail=$qq.'@qq.com';
        $body='https://'.$_SERVER['HTTP_HOST'].'/Index/Forget/ChangePwd.html?qq='.$qq.'&Code='.$VertifyCode;
        $body="亲爱的".$name."同学，您正在找回湖工志愿帮助平台的密码，您的账号为<br>\n".$username."<br>\n，请点击以下链接修改密码：\n<br><a href='".$body."'>".$body."</a>";
        return send_mail($tomail,$name,'志愿平台-找回密码',$body);
    }



    public function forget()    //显示忘记密码页面
    {
        return $this->fetch('index/forget');
    }
    public function ForgetJson()    //忘记密码提交接口
    {
        $qq=input('post.qq');
        $UserData=Db::name('users')->where('qq',$qq)->find();
        if(empty($UserData))
        {
            return json(['result'=>'error','msg'=>'该qq还未注册']);
        }else{
            $username=$UserData['username'];
            $qq=$UserData['qq'];
            $name=$UserData['name'];
            $Code=GetRandStr(30);
            $ExistQQ=Db::name('forget')->where('qq',$qq)->find();
            if(!empty($ExistQQ)){
                Db::name('forget')->where('qq',$qq)->update(['Code'=>$Code]);
            }else{
                Db::name('forget')->insert(['qq'=>$qq,'Code'=>$Code]);
            }
            if($this->SendMail($username,$qq,$name,$Code)){
                return json(['result'=>'success']);
            }else{
                return json(['result'=>'error','mag'=>'未知错误']);
            }
        }
    }
    public function ChangePwd() //改密码部分
    {
        $qq=input('get.qq');
        $Code=input('get.Code');
        $Exist=Db::name('forget')->where(['qq'=>$qq,'Code'=>$Code])->find();
        if(empty($Exist))
        {
            $this->error('参数错误，无法修改');
        }else{
            return $this->fetch('index/ChangePwd');
        }
    }

    public function ChangeJson()    //修改密码接口
    {
        $qq=input('post.qq');
        $Code=input('post.Code');
        $password=input('post.password');
        $Exist=Db::name('forget')->where(['qq'=>$qq,'Code'=>$Code])->find();
        if(empty($Exist))
        {
            return json(["result"=>'error','msg'=>'校验码错误，无法修改']);
        }else{
            $result1=Db::name('forget')->where('Code',$Code)->delete();
            $result2=Db::name('users')->where('qq',$qq)->update(['password'=>md5($password)]);
            if ($result1&&$result2)
            {
                return json(['result'=>'success']);
            }else{
                return json(['result'=>'error','mag'=>'数据库错误']);
            }
        }
    }
}